/*
 * @Author: Zhang Wei
 * @Date: 2022-04-17 20:01:14
 * @LastEditors: Zhang Wei
 * @LastEditTime: 2022-04-17 23:14:31
 * @FilePath: \02_tank\src\service\positionService.ts
 * @Word: There is nothing either good or bad, but thinking makes it so.
 * @Description: 坐标服务
 */
import config from '../config';

type positionType = {
  x: number;
  y: number;
};

class PositionService {
  collectionAll: positionType[] = [];

  // 批量获取位置信息 (去重)
  public getPositionCollection(num: number) {
    const collection: { x: number; y: number }[] = [];

    for (let i = 0; i < num; i++) {
      // 循环判断 去重
      while (true) {
        const position = this.getPosition();
        const isExist = this.collectionAll.some((item: positionType) => {
          return item.x === position.x && item.y === position.y;
        });

        // console.log(JSON.stringify(position), 'position');
        if (!isExist) {
          collection.push(position);
          this.collectionAll.push(position);
          break;
        }
      }
    }

    // console.log(this.collectionAll, 'this.collectionAll');   

    return collection;
  }

  // 获取坐标
  public getPosition() {
    // 顶部空行
    let upEmptyLine = 5;

    // 底部空行
    let downEmptyLine = 2;

    return {
      x:
        Math.floor(Math.random() * (config.canvas.width / config.module.width)) *
        config.module.width,
      y:
        Math.floor(Math.random() * (config.canvas.height / config.module.height - upEmptyLine)) *
          config.module.height +
        config.module.height * downEmptyLine,
    };
  }
}

export default new PositionService();
